import json
from decimal import Decimal
from uuid import UUID

from django.test import TestCase

# Create your tests here.
from django.utils import timezone

from BusinessSubSystem.models import fundField, fund
from CoreSubSystem.models import user
from UserSubSystem.controller import get_all_cards
from UserSubSystem.models import card, rechargeRecord, transactionRecord, asset, profitDetail, userToField, myHolding, \
    fundPlan


# UserSubSystem子应用单元测试
class UserSubSystemTests(TestCase):

    def setUp(self) -> None:
        # 不设置id会出现外键错误  pymysql.err.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`test_fund_project`.`usersubsystem_card`, CONSTRAINT `UserSubSystem_card_user_id_i
        # d_d3796b28_fk_CoreSubSystem_user_id` FOREIGN KEY (`user_id_id`) REFERENCES `coresubsystem_user` (`id`))')
        aUser = user.objects.create(
            id=1,
            user_name="Yiyang",
            user_real_name="陈王艺阳",
            user_password="123456789",
            user_wallet_balance=7777.77,
            user_phone_number="13569998888",
            user_annual_income=5000.00,
            user_expected_time=5,
            user_expected_return_rate=15.55,
            user_risk_ratio=36.78
        )

        user.objects.create(
            id=2,
            user_name="Zhapean",
            user_real_name="张沛然",
            user_password="987654321",
            user_wallet_balance=9999.99,
            user_phone_number="13940138998",
            user_annual_income=10000.00,
            user_expected_time=2,
            user_expected_return_rate=17.32,
            user_risk_ratio=25.43
        )

        card.objects.create(
            id=1,
            card_bank="中国银行",
            card_type="信用卡",
            # 信用卡都为16位
            card_number="1111111111111111",
            card_password="123456",
            card_balance=1234.56,
            card_single_limit=500.00,
            card_daily_limit=1200.00,
            # 外键
            user_id_id=aUser.id
        )

        rechargeRecord.objects.create(
            id=1,
            record_amount=600.75,
            user_id_id=aUser.id
        )

        transactionRecord.objects.create(
            transaction_id= '161ff795-58f5-4f49-bef5-864345920b77',
            operate_type="转入",
            transaction_amount=56.98,
            operate_time=timezone.now(),
            operate_state="已完成",
            operate_finish_time=timezone.now(),
            transaction_source="余额",
            user_id_id=aUser.id
        )

        asset.objects.create(
            id=1,
            asset_amount=99.99,
            yesterday_profit=-57.65,
            holding_profit=779.86,
            cumulative_profit=1875.89,
            user_id_id=aUser.id
        )

        profitDetail.objects.create(
            id=1,
            profitIdate=timezone.now(),
            amount_change=-57.65,
            cumulative_profit=1875.89,
            user_id_id=aUser.id
        )

        aFundField = fundField.objects.create(
            id=1,
            fund_field_name="非银金融"
        )

        userToField.objects.create(
            id=1,
            user_id_id=aUser.id,
            fund_field_id_id=aFundField.id
        )

        aFund = fund.objects.create(
            id=1,
            fund_code="003624",
            fund_name="创金合信资源主题精选股票A",
            fund_type="stock_fund",
            fund_asset_val="950924440.13",
            stock_percent="88.05",
            cash_percent="6.56",
            bond_percent="5.16",
            other_percent="0.23",
            investment_cost_performance_1y="87%",
            risk_control_1y="29%",
            volatility_rank_1y="0.342",
            sharpe_rank_1y="0.1",
            max_draw_down_1y="0.3616",
            investment_cost_performance_3y="89%",
            risk_control_3y="32%",
            volatility_rank_3y="0.3113",
            sharpe_rank_3y="1.15",
            max_draw_down_3y="0.3616",
            nav_grl1m="-5.8908507223",
            nav_grl3m = "-10.7440532826",
            nav_grl6m = "-4.7131480579",
            nav_grl1y = "4.3006448744",
            nav_grl2y = "116.5266365063",
            nav_grl3y = "173.9079654286",
            srank_l1m = "1303/1369",
            srank_l3m = "329/1322",
            srank_l6m = "57/1218",
            srank_l1y = "108/1024",
            srank_l3y = "25/609",
            srank_base = "125/1381"
        )

        myHolding.objects.create(
            id=1,
            fund_amount=3000.00,
            yesterday_profit=-57.65,
            holding_profit=779.86,
            user_id_id=aUser.id,
            fund_id_id=aFund.id
        )

    # card Model单元测试
    def test_card_model(self):
        print("card模型类测试开始")
        result = card.objects.get(id=1)
        self.assertEqual(result.card_bank, "中国银行")
        self.assertEqual(result.card_type, "信用卡")
        self.assertEqual(result.card_number, "1111111111111111")
        self.assertEqual(result.card_password, "123456")
        self.assertEqual(result.card_balance, Decimal('1234.56'))
        self.assertEqual(result.card_single_limit, Decimal('500.00'))
        self.assertEqual(result.card_daily_limit, Decimal('1200.00'))
        self.assertEqual(result.user_id_id, 1)
        print("card模型类测试完成")

    # rechargeRecord Model单元测试
    def test_rechargeRecord_model(self):
        print("rechargeRecord模型类测试开始")
        result = rechargeRecord.objects.get(id=1)
        self.assertEqual(result.record_amount, Decimal('600.75'))
        self.assertTrue(result.operate_time)
        # 打印操作时间（存入数据库时间） 按照年-月-日 时:分:秒
        print("操作时间：" + str(result.operate_time.strftime('%Y-%m-%d %H:%M:%S')))
        self.assertEqual(result.user_id_id,1)
        print("rechargeRecord模型测试完成")

    # transactionRecord Model单元测试
    def test_transactionRecord_model(self):
        print("transactionRecord模型类测试开始")
        result = transactionRecord.objects.get(transaction_id='161ff795-58f5-4f49-bef5-864345920b77')
        self.assertEqual(result.CHANGE_INTO, "转入")
        self.assertEqual(result.TRANSFER_OUT, "转出")
        self.assertEqual(result.transaction_id, UUID('161ff795-58f5-4f49-bef5-864345920b77'))
        self.assertEqual(result.operate_type, "转入")
        self.assertEqual(result.transaction_amount, Decimal('56.98'))
        self.assertTrue(result.operate_time <= result.operate_finish_time)
        self.assertEqual(result.operate_state, "已完成")
        self.assertEqual(result.transaction_source, "余额")
        self.assertEqual(result.user_id_id, 1)
        print("transactionRecord模型类测试完成")

    # asset Model单元测试
    def test_asset_model(self):
        print("asset模型类测试开始")
        result = asset.objects.get(id=1)
        self.assertEqual(result.asset_amount, Decimal('99.99'))
        self.assertEqual(result.yesterday_profit, Decimal('-57.65'))
        self.assertEqual(result.holding_profit, Decimal('779.86'))
        self.assertEqual(result.cumulative_profit, Decimal('1875.89'))
        self.assertEqual(result.user_id_id, 1)
        print("asset模型类测试完成")

    # profitDetail Model单元测试
    def test_profitDetail_model(self):
        print("profitDetail模型类测试开始")
        result = profitDetail.objects.get(id=1)
        print("收益日期：" + result.profitIdate.strftime('%Y-%m-%d'))
        self.assertEqual(result.amount_change, Decimal('-57.65'))
        self.assertEqual(result.cumulative_profit, Decimal('1875.89'))
        self.assertEqual(result.user_id_id, 1)
        print("profitDetail模型类测试完成")

    # userToField Model单元测试
    def test_userToField_model(self):
        print("userToField模型类测试开始")
        result = userToField.objects.get(id=1)
        self.assertEqual(result.user_id_id, 1)
        self.assertEqual(result.fund_field_id_id, 1)
        print("userToField模型类测试完成")

    # myHolding Model单元测试
    def test_myHolding_model(self):
        print("myHolding模型类测试开始")
        result = myHolding.objects.get(id=1)
        self.assertEqual(result.fund_amount, Decimal('3000.00'))
        self.assertEqual(result.yesterday_profit, Decimal('-57.65'))
        self.assertEqual(result.holding_profit, Decimal('779.86'))
        self.assertEqual(result.user_id_id, 1)
        self.assertEqual(result.fund_id_id, 1)
        print("myHolding模型类测试完成")

    # get_all_cards方法测试
    def test_get_all_cards_controller(self):
        print("get_all_cards方法测试开始")
        # 存在该用户
        result = self.client.get("/user/getAllCards?user_id=1")
        print("Yiyang的所有银行卡信息如下：")
        self.assertEqual(json.loads(json.loads(result.content)['data'])[0]['fields']['user_id'], 1)
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 不存在该用户
        result = self.client.get("/user/getAllCards?user_id=3")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_cards方法测试完成")

    # get_all_recharge_records方法测试
    def test_get_all_recharge_records_controller(self):
        print("get_all_recharge_records方法测试开始")
        # 用户存在充值信息
        result = self.client.get("/user/getAllRechargeRecords?user_id=1")
        print("Yiyang的所有的充值信息如下：")
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 用户不存在充值信息
        result = self.client.get("/user/getAllRechargeRecords?user_id=2")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_recharge_records方法测试完成")

    # get_all_transaction_records方法测试
    def test_get_all_transaction_records_controller(self):
        print("get_all_transaction_records方法测试开始")
        # 用户存在交易记录
        result = self.client.get("/user/getAllTransactionRecords?user_id=1")
        print("Yiyang的所有的交易记录如下：")
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 用户不存在交易记录
        result = self.client.get("/user/getAllTransactionRecords?user_id=2")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_transaction_records方法测试完成")

    # get_all_assets方法测试
    def test_get_all_assets_controller(self):
        print("get_all_assets方法测试开始")
        # 用户存在资产对象
        result = self.client.get("/user/getAllAssets?user_id=1")
        print("Yiyang的资产对象列表如下：")
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 用户不存在资产对象
        result = self.client.get("/user/getAllAssets?user_id=2")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_assets方法测试完成")

    # get_all_my_holding方法测试
    def test_get_all_my_holding_controller(self):
        print("get_all_my_holding方法测试开始")
        # 用户存在持有对象
        result = self.client.get("/user/getAllMyHolding?user_id=1")
        print("Yiyang的持有对象如下：")
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 用户不存在持有对象
        result = self.client.get("/user/getAllMyHolding?user_id=2")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_my_holding方法测试完成")

    # get_all_my_profit_details方法测试
    def test_get_all_my_profit_details_controller(self):
        print("get_all_my_profit_details方法测试开始")
        # 用户存在收益明细
        result = self.client.get("/user/getAllMyProfitDetails?user_id=1")
        print("Yiyang的收益明细如下：")
        print(json.loads(result.content)['data'])
        self.assertTrue(json.loads(result.content)['flag'])
        # 用户不存在收益明细
        result = self.client.get("/user/getAllMyProfitDetails?user_id=2")
        self.assertEqual(json.loads(result.content)['data'].__len__(), 0)
        self.assertFalse(json.loads(result.content)['flag'])
        print("get_all_my_profit_details方法测试完成")

    # get_all_fund_plans方法测试
    def test_get_all_fund_plans_controller(self):
        print("get_all_fund_plans方法测试开始")
        fundPlan.objects.create(
            fund_proportion=25.74,
            user_id_id=1,
            fund_id_id=1
        )
        result = self.client.get("/user/getAllFundPlans?user_id=1")
        allFundPlans = json.loads(result.content)['data']
        print(allFundPlans)
        self.assertEqual(allFundPlans[0]['fund_name'], "创金合信资源主题精选股票A")
        self.assertTrue(json.loads(result.content)['flag'])
        print("get_all_fund_plans方法测试完成")


    def tearDown(self) -> None:
        print("-----------------------------")
